import { Router } from 'express';
import { db } from '../services/db';
import { randomInt } from 'crypto';
import { ISmsCodeCache } from '../models/sms-code-cache';
import { ObjectId } from 'mongodb';

export const authRegRouter: Router = Router();


authRegRouter.post("/SendSmsCode", async (req, res, next): Promise<any> => {
    const userId: string = (<any>req).jwtPayload._id;
    const count = await db.users.countDocuments({ mob: req.body.mob, _id: { $ne: <any>new ObjectId(userId) } });
    if (count > 0)
        return res.status(400).json({ title: "手机号已绑定其他用户。" });
    let smsCode = randomInt(1000000, 9999999).toString().substring(0, 6);
    console.info(`${new Date()} ${req.body.mob}: ${smsCode}`);
    // TODO send sms
    await db.smsCodeCaches.replaceOne({ userId }, { mob: req.body.mob, smsCode, userId, createdAt: new Date() }, { upsert: true });
    return res.status(200).json({ isSuccess: true, expireSeconds: 600 });
});

authRegRouter.post(`/VerifySmsCode`, async (req, res, next): Promise<any> => {
    const userId: string = (<any>req).jwtPayload._id;
    var smsCodeCache = await db.smsCodeCaches.findOne({ userId });
    var isSuccess = smsCodeCache?.mob == req.body.mob && smsCodeCache?.smsCode == req.body.smsCode;
    if (isSuccess == true) {
        const user = await db.users.findOneAndUpdate({ _id: <any>new ObjectId(userId) }, { $set: { mob: smsCodeCache?.mob } }, { returnDocument: "after" });
    }
    return res.json({ isSuccess });
});

authRegRouter.post(`/Reg`, async (req, res, next): Promise<any> => {
    const userId: string = (<any>req).jwtPayload._id;
    delete req.body._id;
    const user = await db.users.findOneAndUpdate({ _id: <any>new ObjectId(userId), mob: req.body.mob }, { $set: req.body }, { returnDocument: "after" });
    return res.json({ isSuccess: true, user });
});
